package tech.horgee.log.interceptors;

import cn.hutool.core.util.StrUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import tech.horgee.log.utils.TraceIdUtil;

/**
 * 链路追踪
 */
@Slf4j
@Component
public class TraceHandlerInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        String traceId = request.getHeader(TraceIdUtil.TRACE_ID);
        if (StrUtil.isEmpty(traceId)) {
            TraceIdUtil.setTraceId(TraceIdUtil.generateTraceId());
        } else {
            TraceIdUtil.setTraceId(traceId);
        }
        String url = request.getRequestURI();
        String method = request.getMethod();
        log.info("[{}] => [{}]", method, url);
        response.setHeader(TraceIdUtil.TRACE_ID, TraceIdUtil.getTraceId());
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        TraceIdUtil.clear();
    }
}
